package com.trace.trackshow;


import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Looper;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.leador.api.maps.MapController;
import com.leador.api.maps.MapView;
import com.leador.core.Trace;
import com.leador.listener.OnEntityListener;
import com.leador.listener.OnTrackListener;
import com.leador.location.LocationMode;
import com.leador.manger.LBSTraceClient;
import com.leador.module.TraceLocation;
import com.leador.module.request.Entity;
import com.leador.module.request.Track;
import com.leador.module.response.track.TrackResult;
import com.leador.utils.LogcatHelper;

import java.util.HashMap;
import java.util.Map;


@SuppressLint("NewApi")
public class MainActivity extends FragmentActivity implements OnClickListener {

    /**
     * 轨迹服务
     */
    protected static Trace trace = null;

    /**
     * entity标识
     */
    protected static String entityName = null;

    /**
     * 鹰眼服务ID，开发者创建的鹰眼服务对应的服务ID
     */
    protected static long serviceId = 141352; // serviceId为开发者创建的鹰眼服务ID

    /**
     * 轨迹服务类型（0 : 不建立soket长连接， 1 : 建立socket长连接但不上传位置数据，2 : 建立socket长连接并上传位置数据） 3: http连接
     */
    private int traceType = 2;

    /**
     * 轨迹服务客户端
     */
    protected static LBSTraceClient client = null;

    /**
     * Entity监听器
     */
    protected static OnEntityListener entityListener = null;

    /**
     * Track监听器
     */
    protected static OnTrackListener trackListener = null;

    private Button btnTrackUpload;
    private Button btnTrackQuery;


    /**
     * 用于对Fragment进行管理
     */
    private FragmentManager fragmentManager;

    private TrackUploadFragment mTrackUploadFragment;

    private TrackQueryFragment mTrackQueryFragment;

    protected static Context mContext = null;

    protected static MapView mapView;
    protected static MapController lMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        mContext = getApplicationContext();

        // 初始化轨迹服务客户端
        client = new LBSTraceClient(mContext);

        // 设置定位模式
        client.setLocationMode(LocationMode.High_Accuracy);

        // 初始化entity标识
        entityName = "liuhaiyonglhys@163.com";

        // 初始化轨迹服务
        trace = new Trace(getApplicationContext(), serviceId, entityName,
                traceType);

        // 初始化组件
        initComponent();

        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);// 此方法必须重写

        init();

        // 初始化OnEntityListener
        initOnEntityListener();

        // 初始化OnTrackListener
        initOnTrackListener();

        addEntity();

        // 设置默认的Fragment
        setDefaultFragment();

    }

    /**
     * 添加Entity
     */
    private void addEntity() {
        Geofence.addEntity();
        Track track = new Track();
        track.setServiceId(serviceId);
        track.setColumnKey("hello");
        track.setColumnDesc("hello");
        track.setColumTyppe(3);
        MainActivity.client.addTrackcolumn(track,MainActivity.trackListener);
        test();
    }

    public void test(){
        Entity en = new Entity();
        en.setServiceId(MainActivity.serviceId);
        en.setColumnKey("testaddEntitycolumn");
        en.setColumnDesc("测试描述");
        en.setIsSearch(String.valueOf(1));
        MainActivity.client.addEntitycolumn(en,entityListener);
    }

    /**
     * 初始化组件
     */
    private void initComponent() {
        // 初始化控件
        btnTrackUpload = (Button) findViewById(com.trace.trackshow.R.id.btn_trackUpload);
        btnTrackQuery = (Button) findViewById(com.trace.trackshow.R.id.btn_trackQuery);
        btnTrackUpload.setOnClickListener(this);
        btnTrackQuery.setOnClickListener(this);
        fragmentManager = getSupportFragmentManager();
    }

    /**
     * 设置默认的Fragment
     */
    private void setDefaultFragment() {
        handlerButtonClick(com.trace.trackshow.R.id.btn_trackUpload);
    }

    /**
     * 点击事件
     */
    public void onClick(View v) {
        // TODO Auto-generated method stub
        handlerButtonClick(v.getId());
    }

    /**
     * 初始化OnEntityListener
     */
    private void initOnEntityListener() {
        entityListener = new OnEntityListener() {

            // 请求失败回调接口
            @Override
            public void onRequestFailedCallback(com.leador.module.response.Result result) {
//                Looper.prepare();
                Toast.makeText(getApplicationContext(),
                        "entity请求失败回调接口消息 : " + result.getMessage(), Toast.LENGTH_SHORT)
                        .show();
//                Looper.loop();
            }


            @Override
            public void onReceiveLocation(TraceLocation location) {
                // TODO Auto-generated method stub
                if (mTrackUploadFragment != null) {
                    mTrackUploadFragment.showRealtimeTrack(location);
                }
            }

        };
    }

    /**
     * 初始化OnTrackListener
     */
    private void initOnTrackListener() {

        trackListener = new OnTrackListener() {
            @Override
            public void onRequestSucessCallback(String result) {

            }

            // 请求失败回调接口


            @Override
            public void onRequestFailedCallback(com.leador.module.response.Result result) {
                if(result == null){
                    return;
                }
                Looper.prepare();
                Toast.makeText(MainActivity.this, "track请求失败回调接口消息 : " + result.getMessage(), Toast.LENGTH_SHORT).show();
                Looper.loop();
            }

            @Override
            public void onQueryHistoryTrackCallback(TrackResult result) {
                lMap.clear();
                mTrackQueryFragment.showHistoryTrack(result);
            }

            @Override
            public Map onTrackAttrCallback() {
                Map<String,String> stringHashMap= new HashMap<String, String>();
                stringHashMap.put("hello","test");
                stringHashMap.put("hello1","test1");
                stringHashMap.put("hello2","test2");
                stringHashMap.put("hello3","test3");
                return stringHashMap;
            }
        };
    }

    /**
     * 处理tab点击事件
     *
     * @param id
     */
    private void handlerButtonClick(int id) {
        // 重置button状态
        onResetButton();
        // 开启Fragment事务
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        // 隐藏Fragment
        hideFragments(transaction);

        switch (id) {
            case R.id.btn_trackQuery:
                TrackUploadFragment.isInUploadFragment = false;
                if (mTrackQueryFragment == null) {
                    mTrackQueryFragment = new TrackQueryFragment();
                    transaction.add(com.trace.trackshow.R.id.fragment_content, mTrackQueryFragment);
                } else {
                    transaction.show(mTrackQueryFragment);
                }
                mTrackQueryFragment.addMarker();
                btnTrackQuery.setTextColor(Color.rgb(0x00, 0x00, 0xd8));
                btnTrackQuery.setBackgroundColor(Color.rgb(0x99, 0xcc, 0xff));
                mTrackUploadFragment.startQueryRealTimeTrack();
                break;
            case R.id.btn_trackUpload:
                TrackUploadFragment.isInUploadFragment = true;
                if (mTrackUploadFragment == null) {
                    mTrackUploadFragment = new TrackUploadFragment();
                    transaction.add(R.id.fragment_content, mTrackUploadFragment);
                } else {
                    transaction.show(mTrackUploadFragment);
                }

                btnTrackUpload.setTextColor(Color.rgb(0x00, 0x00, 0xd8));
                btnTrackUpload.setBackgroundColor(Color.rgb(0x99, 0xcc, 0xff));
                break;
        }
        // 事务提交
        transaction.commit();
    }

    /**
     * 重置button状态
     */
    private void onResetButton() {
        btnTrackQuery.setTextColor(Color.rgb(0x00, 0x00, 0x00));
        btnTrackQuery.setBackgroundColor(Color.rgb(0xFF, 0xFF, 0xFF));
        btnTrackUpload.setTextColor(Color.rgb(0x00, 0x00, 0x00));
        btnTrackUpload.setBackgroundColor(Color.rgb(0xFF, 0xFF, 0xFF));
    }

    /**
     * 隐藏Fragment
     */
    private void hideFragments(FragmentTransaction transaction) {

        if (mTrackQueryFragment != null) {
            transaction.hide(mTrackQueryFragment);
        }
        if (mTrackUploadFragment != null) {
            transaction.hide(mTrackUploadFragment);
        }
        // 清空地图覆盖物
        mapView.getMap().clear();
    }
    /**
     * 初始化LMap对象
     */
    private void init() {
        if (lMap == null) {
            lMap = mapView.getMap();
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        TrackUploadFragment.isInUploadFragment = false;
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        client.onDestroy();
        android.os.Process.killProcess(android.os.Process.myPid());
        mapView.onDestroy();
    }

}
